package control

import (
	"fmt"
	"manager/model"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/lerryxiao/gin"
	"hiscene.com/openplatform/common/logger"
	"hiscene.com/openplatform/common/retCode"
)

// boardInfo 开发板信息
func boardInfo(c *gin.Context) {
	smac := c.Request.FormValue("mac")
	if len(smac) > 0 {
		board := GetBoard(smac)
		if board == nil {
			c.JSON(http.StatusOK, gin.H{"retCode": retCode.E_C_BAD_PARAM, "comment": "找不到对应mac信息"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"retCode": retCode.S_OK, "data": []interface{}{board}})
	} else {
		c.JSON(http.StatusOK, gin.H{"retCode": retCode.S_OK, "data": boards})
	}
}

// boardEdit 板子编辑
func boardEdit(c *gin.Context) {
	board := getBoard(c)
	if board == nil {
		return
	}

	bchange := false
	name := c.Request.FormValue("name")
	if len(name) > 0 && board.Name != name {
		board.Name = name
		bchange = true
	}

	disable := c.Request.FormValue("disable")
	if len(disable) > 0 {
		switch disable {
		case "false", "False", "0":
			{
				if board.Disable == true {
					board.Disable = false
					bchange = true
				}
			}
		case "true", "TRUE", "1":
			{
				if board.Disable == false {
					board.Disable = true
					bchange = true
				}
			}
		}
	}

	if bchange == true {
		SaveBoard(board)
		c.JSON(http.StatusOK, gin.H{"retCode": retCode.S_OK, "comment": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"retCode": retCode.S_OK, "comment": "no changed"})
	}
}

////////////////////////////////////////////////////////////////////////////////

// TickInfo 心跳信息
type TickInfo struct {
	IP   string    `json:"ip"`
	Mac  string    `json:"mac"`
	Sync bool      `json:"sync"`
	Pins []TickPin `json:"pins"`
}

// TickPin 心跳端口
type TickPin struct {
	Name  string `json:"name"`
	OnOff bool   `json:"onoff"`
}

// RefreshBoard 刷新开发板
func RefreshBoard(info *TickInfo) {
	if info == nil || len(info.Mac) <= 0 {
		return
	}

	board, bsave, nboard := GetBoard(info.Mac), true, false
	if board != nil {
		if board.IP == info.IP {
			bsave = false
		} else {
			board.IP = info.IP
		}
	} else {
		board = &model.Board{
			Mac:     info.Mac,
			IP:      info.IP,
			StartTM: time.Now().Unix(),
		}
		nboard = true
	}

	board.TickTM = time.Now().Unix()
	if bsave == true {
		SaveBoard(board)
		if nboard == true {
			for _, pin := range info.Pins {
				lamp := GetLamp(board.ID, pin.Name)
				if lamp == nil {
					lamp = &model.Lamp{
						BoardID: board.ID,
						Key:     pin.Name,
						OnOff:   pin.OnOff,
					}
					SaveLamp(lamp)
				}
			}
		}
		logger.Log4g.Trace("tick info: %v", *info)
	}
}

// GetBoardState 获取开发板信息
func GetBoardState(mac string) string {
	board := GetBoard(mac)
	if board == nil || board.ID <= 0 {
		return ""
	}

	value := ""
	for _, lamp := range lamps {
		if lamp == nil || lamp.BoardID != board.ID {
			continue
		}
		if lamp.OnOff == true {
			value += fmt.Sprintf("%v:1,", lamp.Key)
		} else {
			value += fmt.Sprintf("%v:0,", lamp.Key)
		}
	}

	return value
}

////////////////////////////////////////////////////////////////////////////////

func inetNtoa(ip int64) string {
	return fmt.Sprintf("%d.%d.%d.%d", byte(ip), byte(ip>>8), byte(ip>>16), byte(ip>>24))
}

func getBoolean(str string) bool {
	val, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		logger.Log4g.Error("tick info getBoolean error: %v, str: %v", err, str)
		return false
	}
	if val > 0 {
		return true
	}
	return false
}

// Init 初始化
func (info *TickInfo) Init(data string) {
	datas := strings.Split(data, "|")
	ldata := len(datas)
	if ldata > 0 {
		info.Mac = datas[0]
	}
	if ldata > 1 {
		val, err := strconv.ParseInt(datas[1], 10, 64)
		if err != nil {
			logger.Log4g.Error("tick info init error: %v", err)
		} else {
			info.IP = inetNtoa(val)
		}
	}
	if ldata > 2 {
		info.Sync = getBoolean(datas[2])
	}
	if ldata > 3 {
		info.Pins = make([]TickPin, 0)
		dstr := datas[3]
		lstr := len(dstr)
		if lstr > 0 {
			if dstr[0] == '[' {
				dstr = dstr[1:]
				lstr = lstr - 1
			}
			if dstr[lstr-1] == ']' {
				dstr = dstr[:lstr-1]
				lstr = lstr - 1
			}
		}
		for _, str := range strings.Split(dstr, ",") {
			if len(str) > 0 {
				ss := strings.Split(str, ":")
				if len(ss) == 2 {
					info.Pins = append(info.Pins, TickPin{
						Name:  ss[0],
						OnOff: getBoolean(ss[1]),
					})
				}
			}
		}
	}
}
